<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问卷名称" prop="surveyName">
        <el-input style="width: 200px" v-model="queryParams.surveyName" placeholder="请输入问卷名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="问卷类型" prop="surveyType">
        <el-select style="width: 200px" v-model="queryParams.surveyType" placeholder="请选择问卷类型" clearable>
          <el-option v-for="dict in dict.survey_type" :key="dict.dictValue" :label="dict.dictName" :value="dict.dictValue"/>
        </el-select>
      </el-form-item>

      <el-form-item label="问卷状态" prop="surveyStatus">
        <el-select style="width: 200px" v-model="queryParams.surveyStatus" placeholder="请选择问卷状态" clearable>
          <el-option v-for="dict in dict.survey_status" :key="dict.dictValue" :label="dict.dictName" :value="dict.dictValue"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" @click="handleAdd" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Promotion" :disabled="multiple" @click="handlePublish" >发布</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete" >删除</el-button>
      </el-col>
    </el-row>
    <br />
    <el-table v-loading="loading" :data="surveyList" stripe table-layout="fixed" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="问卷名称" prop="surveyName" />
      <el-table-column label="问卷描述" prop="surveyDesc" show-overflow-tooltip />
      <el-table-column label="问卷类型" prop="surveyType">
        <template #default="scope">
          <template v-for="item in dict.survey_type" :key="item.dictValue">
            <el-tag v-if="item.dictValue == scope.row.surveyType" :type="item.cssClass">
              {{ item.dictName }}
            </el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="问卷状态" prop="surveyStatus">
        <template #default="scope">
          <template v-for="item in dict.survey_status" :key="item.dictValue">
            <el-tag v-if="item.dictValue == scope.row.surveyStatus" :type="item.cssClass">
              {{ item.dictName }}
            </el-tag>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template #default="scope">
          <el-button size="small" type="primary" text icon="DocumentAdd" @click="handleDesign(scope.row)" v-if="scope.row.surveyStatus == '0'" >设计</el-button>
          <el-button size="small" type="primary" text icon="View" @click="handlePreview(scope.row)" >预览</el-button>
          <el-button size="small" type="primary" text icon="Refresh" @click="handleRevoke(scope.row)" v-if="scope.row.surveyStatus == '1'" >撤销发布</el-button>

          <el-dropdown class="showcase" v-if="scope.row.surveyStatus == '0'">
            <span class="el-dropdown-link">
              更多
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button size="small" type="primary" text icon="Position" @click="handlePublish(scope.row)" v-if="scope.row.surveyStatus == '0'" >发布</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button size="small" type="primary" text icon="CopyDocument" @click="handleCopy(scope.row)" v-if="scope.row.surveyStatus == '0'" >复制</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button size="small" type="primary" text icon="edit" @click="handleUpdate(scope.row)" v-if="scope.row.surveyStatus == '0'" >修改</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button size="small" type="danger" text icon="delete" @click="handleDelete(scope.row)" v-if="scope.row.surveyStatus == '0'" >删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 10px"
      size="small" 
      layout="prev, pager, next, jumper, ->, total"
      :total="total"
      :page-size="queryParams.pageSize"
      :current-page="queryParams.pageNum"
      @current-change="getList"
    />

    <!-- 添加或修改问卷对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body>
      <el-form ref="dialogForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问卷名称" prop="surveyName">
          <el-input v-model="form.surveyName" placeholder="请输入问卷名称" />
        </el-form-item>
        <el-form-item label="问卷类型" prop="surveyType">
          <el-select v-model="form.surveyType" placeholder="请选择问卷类型">
            <el-option v-for="dict in dict.survey_type" :key="dict.dictValue" :label="dict.dictName" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="选择模板">
          <el-tag style="margin-right: 10px;" v-if="tempIds.length > 0" closable @close="delTemplate" type="success">{{ temp.surveyName }}</el-tag>
          <el-button type="primary" plain icon="CirclePlus" @click="chooseTemplate" >选择模板</el-button>
        </el-form-item>
        <el-form-item label="问卷描述" prop="surveyDesc">
          <el-input v-model="form.surveyDesc" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

      <!---选择模板--->
      <el-dialog title="选择模板" v-model="topen" append-to-body>
        
        <el-card class="tb-card" v-for="row in templateList" :key="row.surveyId">
          <template #header>
            <div class="card-header">
              <el-checkbox-group v-model="tempIds" @change="changeTemplate">
                <el-checkbox style="margin-right: 4px;vertical-align: -2px;" :value="row.surveyId">{{ row.surveyName }}</el-checkbox>
              </el-checkbox-group>
              <template v-for="item in dict.survey_type" :key="item.dictValue">
                <el-tag v-if="item.dictValue == row.surveyType" :type="item.cssClass">{{ item.dictName }}</el-tag>
              </template>
            </div>
          </template>
          <div class="card-body">
            <p>{{ row.surveyDesc }}</p>
          </div>
        </el-card>
      </el-dialog>
  </div>
</template>

<script>
import {
  listSurvey,
  getSurvey,
  removeSurvey,
  addOrUpdateSurvey,
  publishSurvey,
  copySurvey,
  revokeSurvey,
  copyByTemplate
} from "@/api/survey/survey";
import { getDicts } from "@/api/dict";
import { ElMessageBox } from 'element-plus'

export default {
  name: "Survey",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷表格数据
      surveyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        surveyName: null,
        surveyDesc: null,
        surveyType: null,
        surveyStatus: null,
        status: "1",
        isTemplate: '0',
      },
      // 表单参数
      form: {
        surveyId: null,
        surveyName: null,
        surveyDesc: null,
        surveyType: null,
        surveyStatus: null,
        createTime: null,
        status: "1",
        isTemplate: '0',
      },
      // 表单校验
      rules: {
        surveyName: [
          { required: true, message: "问卷名称不能为空", trigger: "blur" },
        ],
      },
      dict: {
        survey_type: [],
        survey_status: [],
      },

      topen: false,
      templateList: [],
      tempIds: [],
      temp: {}
    };
  },
  async created() {
    this.getList();
    this.dict.survey_status = await getDicts("survey_status");
    this.dict.survey_type = await getDicts("survey_type");
  },
  methods: {
    /** 查询问卷列表 */
    getList() {
      this.loading = true;
      listSurvey(this.queryParams).then((response) => {
        this.surveyList = response.records;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        surveyId: null,
        surveyName: null,
        surveyDesc: null,
        surveyType: null,
        surveyStatus: null,
        status: "1",
        isTemplate: '0',
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.surveyId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加问卷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const surveyId = row.surveyId || this.ids;
      getSurvey(surveyId).then((response) => {
        this.form = response;
        this.open = true;
        this.title = "修改问卷";
      });
    },
    /** 发布按钮操作 */
    handlePublish(row) {
      //this.reset();
      const surveyId = row.surveyId || this.ids;
      ElMessageBox.confirm('确定要发布这些问卷吗？','警告',
        {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}
      ).then(() => {
        publishSurvey(surveyId).then((response) => {
          this.$message({message: '发布成功',type:'success'});
          this.getList();
        });
      }).catch(() => {});
    },
    /** 撤销发布按钮操作 */
    handleRevoke(row) {
      const surveyId = row.surveyId;
      ElMessageBox.confirm('确定要撤销发布该问卷吗？','警告',
        {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}
      ).then(() => {
        revokeSurvey(surveyId).then((response) => {
          console.log(response);
          this.$message({message: '撤销成功',type:'success'});
          this.getList();
        });
      }).catch(() => {});
    },
    /** 设计按钮操作 */
    handleDesign(row) {
      const surveyId = row.surveyId;
      this.$router.push({
        path: "/surdes/design",
        query: { surveyId: surveyId },
      });
    },
    /** 复制按钮操作 */
    handleCopy(row) {
      const surveyId = row.surveyId;
      copySurvey(surveyId).then(() => {
        this.$message({message: '复制成功',type:'success'});
        this.getList();
      });
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      var routeUrl = this.$router.resolve({
        path: `/preview/${row.surveyId}`,
      });
      window.open(routeUrl.href, "_blank");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if(this.tempIds.length > 0){
            this.form.surveyId = this.tempIds[0];
            copyByTemplate(this.form).then(() => {
              this.$message({message: '保存成功',type:'success'});
              this.open = false;
              this.getList();
            })
          } else {
            addOrUpdateSurvey(this.form).then((response) => {
              this.$message({message: '保存成功',type:'success'});
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const surveyIds = row.surveyId || this.ids;
      ElMessageBox.confirm('是否确认删除问卷编号为" ' + surveyIds + ' "的问卷吗？','警告',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
          await removeSurvey(surveyIds);
          this.getList();
          this.$message({message: '删除成功',type:'success'});
      }).catch(() => {});
    },
    chooseTemplate(){
      this.topen = true;
      listSurvey({isTemplate: '1'}).then((response) => {
        this.templateList = response.records;
      });
    },
    changeTemplate(){
      if(this.tempIds.length > 1){
        this.tempIds.splice(0,1);
      }
      this.temp = this.templateList.find(item => item.surveyId == this.tempIds[0]);
    },
    delTemplate(){
      this.temp = {};
      this.tempIds = [];
    }
  },
};
</script>

<style scoped>
.tb-card{
    display: inline-block;
    max-width: 180px;
    margin-top: 10px;
    margin-right: 20px;
  }
  .tb-card .card-body{
    min-height: 45px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
.el-button.el-button--small.is-text{
  padding: 0 4px;
  margin: 0;
}
.showcase {
  font-size: 12px;
  vertical-align: middle;
  margin-left: 10px;
}
.showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
